<template>
  <view class="details">
    <cover-view
      class="nav"
      :style="{
        paddingTop: statusBarHeight + 'px',
      }"
    >
      <cover-view class="nav-head">
        <cover-image
          class="img"
          :src="asyncImgs.common.back"
          mode="widthFix"
          @click="$utils.goBack()"
        />
      </cover-view>
    </cover-view>

    <view class="uni-padding-wrap" v-if="data">
      <view class="page-section swiper">
        <view class="page-section-spacing">
          <swiper
            class="swiper"
            @change="changefun"
            @animationfinish="animationfinishfun"
            :current="current"
            :vertical="true"
          >
            <swiper-item
              v-for="(item, index) in list"
              :key="item.id"
              @longpress.stop="longpress(item)"
            >
              <view class="swiper-item">
                <video
                  v-if="current < index + 3 && current > index - 3"
                  :custom-cache="false"
                  loop="true"
                  class="video"
                  :id="'id' + index"
                  :enable-play-gesture="true"
                  :enable-progress-gesture="true"
                  :controls="false"
                  :src="item.video_url"
                  :show-center-play-btn="false"
                ></video>
              </view>

              <pageContent
                v-show="is_active"
                :data="getItemInfo"
                :userId="userId"
                :videoId="id"
                @openPop="openPop"
                @changeStatus="changeStatus"
                @confirm="confirm"
              ></pageContent>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </view>

    <detailsShare
      v-if="showGoodsShare"
      :topic_id="getItemInfo.id ? getItemInfo.id : id"
      @closeShare="showGoodsShare = false"
    ></detailsShare>

    <pageGoods
      ref="pageGoods"
      :items="getItemComment.list"
      :videoId="id"
    ></pageGoods>

    <u-popup
      mode="bottom"
      v-model="showPopup"
      :z-index="121"
      safe-area-inset-bottom
      border-radius="24"
    >
      <view class="pop">
        <scroll-view scroll-y class="scrollY">
          <detailsContent
            :data="{
              ...getItemInfo,
              id,
            }"
            :userId="userId"
            :videoId="id"
            @follow="follow"
          ></detailsContent>

          <detailsComment
            :items="getItemComment.list"
            :count="getItemComment.count"
            :userId="author_id"
            @comment="openPop"
          ></detailsComment>
        </scroll-view>
      </view>

      <detailsFooter
        :data="getItemInfo"
        :placeholder="placeholder"
        @confirm="confirm"
        @setParentId="openPop"
        @changeStatus="changeStatus"
        ref="footer"
      ></detailsFooter>
    </u-popup>

    <u-popup
      mode="bottom"
      v-model="showPopMenu"
      border-radius="24"
      safe-area-inset-bottom
      :maskCloseAble="false"
    >
      <view class="popBox">
        <view class="popup-title">
          <view class="let"> {{ $t("videoGoods.detail.noLike") }} </view>

          <i class="iconfont icon-close" @click="showPopMenu = false"></i>
        </view>

        <view
          class="popItem"
          @click="
            $utils.toUrl(`/videoGoods/report/index?id=${item.id}`, 'navigate')
          "
        >
          <i class="iconfont icon-prompt"></i>
          <view class="text">{{ $t("videoGoods.detail.accusation") }}</view>
          <i class="iconfont icon-arrow-right"></i>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import videoClassify from "@/api/videoClassify";
import detailsContent from "../components/details-content";
import detailsComment from "../components/details-comment";
import detailsFooter from "../components/details-footer";
import detailsShare from "../components/details-share";
import pageContent from "./components/page-content";
import pageGoods from "./components/page-goods";

export default {
  components: {
    detailsContent,
    detailsComment,
    detailsFooter,
    detailsShare,
    pageContent,
    pageGoods,
  },

  data() {
    return {
      data: null,
      list: [],

      index_: 0,
      current: 0,
      is_active: true,

      page: 1,
      count: 0,
      limit: 5,
      isEnd: false,
      id: undefined,
      userId: undefined,

      parent_id: 0,
      top_parent_id: 0,
      placeholder: "",

      commentList: {},

      showGoodsShare: false,
      showPopup: false,
      showPopMenu: false,
      author_id: undefined,

      item: null,
    };
  },

  computed: {
    getItemInfo() {
      let { list, current } = this;
      if (!list.length) {
        return null;
      }

      return list[current];
    },

    getItemComment: {
      get() {
        let { getItemInfo, commentList, id } = this;
        let _id = id;

        if (getItemInfo) {
          _id = getItemInfo.id;
        }

        let item = this.list.find((el) => String(el.id) === String(_id));

        if (item) {
          return commentList[item.id];
        }

        return {
          list: [],
          count: 0,
        };
      },
    },
  },

  onLoad(opi) {
    if (opi && opi.id) {
      this.id = opi.id;
    }

    if (opi?.scene) {
      let scene = decodeURIComponent(opi.scene);
      let params = this.$utils.sceneDecode(scene);
      this.id = params.vid;
    }

    this.getData();

    try {
      const userInfo = uni.getStorageSync("userInfo");
      if (userInfo) {
        this.userId = userInfo.id;
      }
    } catch (e) {}
  },

  // onShow() {
  //   // 执行暂停播放 start
  //   let { index_ } = this,
  //     videoContext = uni.createVideoContext("id" + index_);

  //   videoContext.play();
  // },

  methods: {
    videoGoodsList(is = false) {
      let { list: oldList, page } = this,
        limit = 3;

      videoClassify
        .videoGoodsList({
          limit,
          page,
          type: "1",
        })
        .then((res) => {
          if (res.code === 0) {
            let { list, row_count } = res.data;
            this.count = parseInt(row_count);
            if (list.length) {
              // 去除重复的详情
              let index = list.findIndex(
                (el) => String(el.id) === String(this.id)
              );
              if (index !== -1) {
                list.splice(index, 1);
              }
              oldList.push(...list);

              this.page = this.page + 1;
            }

            if (oldList.length > this.count) {
              this.isEnd = true;
            }

            if (is) {
              let { id, data } = this;

              this.count += 1;
              oldList.unshift({
                id,
                autoplay: false,
                ...data,
              });

              this.init();
            }
          }
        });
    },

    async getData() {
      let msg = await videoClassify.videoGoodsDetail({
        id: this.id,
      });

      if (msg.code === 0) {
        this.data = msg.data;
        this.author_id = msg.data.user_id;

        if (msg.data.douyin_url) {
          uni.setClipboardData({
            data: msg.data.douyin_url,
            success() {
              uni.hideToast();
            }
          });
        }
      }
      this.getCommentData(this.id);
      this.videoGoodsList(true);
    },

    getCommentData(id, _is = false) {
      let { commentList } = this;

      if (!commentList[id]) {
        commentList[id] = {
          page: 1,
          list: [],
          count: 0,
          isEnd: false,
        };
      }

      if (commentList[id].isEnd) {
        return;
      }

      let oldList = commentList[id].list;

      videoClassify
        .videoGoodsCommentList({
          vl_id: id,
          page: commentList[id].page,
          limit: 10,
        })
        .then((res) => {
          if (res.code === 0) {
            let { list, row_count } = res.data;
            commentList[id].count = parseInt(row_count);

            if (list.length) {
              oldList.push(...list);
              commentList[id].page++;
            }

            if (oldList.length >= commentList[id].count) {
              commentList[id].isEnd = true;
            }

            if (_is) {
              let newCommentList = JSON.parse(JSON.stringify(commentList));
              this.commentList = null;
              this.commentList = newCommentList;
            }
          }
        });
    },

    changefun(e) {
      this.is_active = false;

      this.current = e.detail.current;

      // 执行暂停播放 start
      let { index_ } = this,
        videoContext = uni.createVideoContext("id" + index_);

      videoContext.pause();
      // 执行暂停播放 end!

      // 获取评论数据
      this.getCommentData(this.getItemInfo.id);
    },

    animationfinishfun(e) {
      let { index_, list, isEnd } = this;
      let current = e.detail.current;
      this.is_active = true;

      // 执行暂停播放 start
      let videoContext = uni.createVideoContext("id" + index_);
      videoContext.pause();
      videoContext = uni.createVideoContext("id" + current);
      videoContext.play();
      this.index_ = current;

      // 执行暂停播放 end!

      // 获取更多视频
      if (list.length <= current + 2 && !isEnd) {
        this.videoGoodsList();
      }
    },

    init() {
      this.$nextTick(function () {
        let videoContext = uni.createVideoContext("id0");
        videoContext.play();
      });
    },

    openPop(type) {
      switch (type) {
        case 1:
          this.showPopup = true;
          break;

        case 2:
          let { getItemInfo } = this;
          if (getItemInfo) {
            this.$refs.pageGoods.goodsList = {
              count: getItemInfo.goods
                ? getItemInfo.goods.count
                : getItemInfo.goods_list.length,
              list: getItemInfo.goods
                ? getItemInfo.goods.list
                : getItemInfo.goods_list,
            };
            this.$refs.pageGoods.showPopup = true;
          }
          break;
      }
    },

    // 转发点赞收藏
    changeStatus(type, status, numEl) {
      let isCancel = false,
        { getItemInfo, list } = this,
        data = list.find((el) => el.id === getItemInfo.id);

      if ((type === "is_like" || type === "is_collect") && data[type] === 1) {
        isCancel = true;
      } else if (type === "trans_count") {
        this.showGoodsShare = true;
      }

      if (!isCancel) {
        videoClassify
          .videoGoodsVote({
            vl_id: data.id,
            type: status,
          })
          .then((res) => {
            if (res.code === 0) {
              this.$u.toast(res.msg);
              if (numEl) {
                this.$nextTick(() => {
                  this.$set(data, type, 1);
                  this.$set(data, numEl, parseInt(data[numEl]) + 1);

                  // 单个数据
                  // this.$set(getItemInfo, type, 1);
                  // this.$set(
                  //   getItemInfo,
                  //   numEl,
                  //   parseInt(getItemInfo[numEl]) + 1
                  // );
                });
              } else {
                this.$nextTick(() => {
                  this.$set(data, type, parseInt(data[type]) + 1);
                });
              }
            }
          });
        return;
      }

      videoClassify
        .videoGoodsCancelVote({
          vl_id: data.id,
          type: status,
        })
        .then((res) => {
          if (res.code === 0) {
            this.$nextTick(() => {
              this.$set(data, type, 0);
              this.$set(data, numEl, parseInt(data[numEl]) - 1);
            });
          }
        });
    },

    // 提交评论
    confirm(content) {
      let { parent_id, top_parent_id, getItemInfo, list, commentList } = this,
        data = list.find((el) => el.id === getItemInfo.id);

      uni.showLoading({
        title: this.$t("home.loading"),
      });

      videoClassify
        .videoGoodsSubmitComment({
          parent_id,
          content,
          vl_id: data.id,
          top_parent_id,
        })
        .then((res) => {
          uni.hideLoading();

          if (res.code === 0) {
            // let newObj = {};
            // for (let i in commentList) {
            //   if (String(i) === String(data.id)) {
            //     continue;
            //   }
            //   newObj[i] = commentList[i];
            // }

            // // this.$nextTick(() => {
            // this.commentList = newObj;
            // // });
            this.commentList[data.id] = {
              page: 1,
              list: [],
              count: 0,
              isEnd: false,
            };

            this.getCommentData(data.id, true);

            this.$utils.toast(res.mes, "success");
            let { footer } = this.$refs;
            footer.showPopup = false;
            footer.content = "";
            this.parent_id = 0;
            this.top_parent_id = 0;
            this.placeholder = "";
          }
        })
        .catch(() => {
          uni.hideLoading();
        });
    },

    // 关注和取消关注
    follow() {
      let { getItemInfo, list } = this,
        data = list.find((el) => el.id === getItemInfo.id),
        { is_focus, user_id } = data;

      if (is_focus === 0) {
        videoClassify
          .videoGoodsFocus(
            {
              focus_user_id: user_id,
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              this.$set(data, "is_focus", 1);
              this.$utils.toast(res.msg);
            }
          });
      } else {
        videoClassify
          .videoGoodsCancelFocus(
            {
              user_id,
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              this.$set(data, "is_focus", 0);
              this.$utils.toast(res.msg);
            }
          });
      }
    },

    longpress(item) {
      this.item = item;
      this.showPopMenu = true;
    },
  },

  onShareTimeline() {
    let { data } = this;

    return {
      title: data.title,
      path: "",
      imageUrl: data.cover_pic,
    };
  },
};
</script>

<style scoped lang="less">
.details {
  position: relative;
  height: 100vh;
  background: #000;
}

.video {
  width: 100%;
  height: 100%;
  position: relative;
}

.swiper {
  height: 100vh;
  transition: 0.2s linear;

  .swiper-item {
    height: 100%;
    position: relative;
  }
}

.nav {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: 9;
  padding: 0 32rpx;

  .nav-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
  }

  .img {
    width: 19rpx;
    height: auto;
  }
}

.scrollY {
  max-height: 50vh;
}

.pop {
  padding: 30rpx 0;
}

.popBox {
  display: flex;
  flex-direction: column;
  padding: 0 36rpx;
}

.popup-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 0;

  .let {
    font-size: 32rpx;
    color: #262626;
    font-weight: bold;
  }

  .iconfont {
    color: #262626;
  }
}

.popItem {
  display: flex;
  align-items: center;
  height: 120rpx;
  border-bottom: 1px solid #f8f8f8;

  &:last-of-type {
    border-bottom: 0;
  }

  .text {
    position: relative;
    top: -4rpx;
    padding: 0 15rpx;
    font-size: 28rpx;
    color: #262626;
    font-weight: bold;
    color: #333;
    flex: 1;
    overflow: hidden;
  }

  .icon-prompt {
    font-size: 50rpx;
    color: #8c8c8c;
  }

  .icon-arrow-right {
    font-size: 22rpx;
  }
}
</style>
